<template>
  <contentModel :title="props.title" :has-footer="false" @close="handleClose">
    <query-page
      ref="queryPageComp"
      v-model:selectedKeys="selectedKeys"
      :table-render-config="columns"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="subtableListData"
      :total="total"
      :has-line="true"
      :split-no-left="false"
      :split-size="0.2"
      height="calc(100% - 50px)"
      row-selection-type="checkbox"
      empty="暂无数据,请先填写控制清单信息"
      @query-data="getData"
    >
      <template #split-left>
        <div class="leftbox">
          <a-form
            ref="formRef"
            :model="form"
            :style="{
              width: '100%',
              height: 'calc(100% - 50px)',
              overflow: 'auto',
              paddingBottom: '20px',
            }"
            layout="vertical"
            :rules="rules"
            @submit="handleSubmit"
          >
            <a-form-item
              field="secretLevel"
              label="密级"
              :disabled="mainTableId || props.title === '编辑'"
              label-col-flex="100px"
              :validate-trigger="['blur']"
            >
              <secretLevelSelect
                v-model="form.secretLevel"
                :default-value="form.secretLevel"
                :isShowClearTip="true"
                @change="secretLevelChange"
              />
            </a-form-item>
            <a-form-item field="billNo" label="单据编号" label-col-flex="100px">
              <a-input
                v-model="form.billNo"
                placeholder="后台自动生成"
                disabled
              />
            </a-form-item>
            <a-form-item field="projectId" label="机型" label-col-flex="100px">
              <inputModal
                v-model="form.projectId"
                :label-value="form.projectName"
                :value-name="'id'"
                :label-name="'materialCode'"
                :default-query="{
                  materialType: '6',
                  secretLevel: form.secretLevel,
                }"
                :title="'机型'"
                :disabled="!form.secretLevel"
                :type="'materialCode'"
                @show-tips="projectIdTips"
                @handle-ok="(row) => selectSupplier(row)"
              />
            </a-form-item>
            <a-form-item
              field="zeroCategoryCode"
              label="零级品类"
              label-col-flex="100px"
            >
              <dict-select
                v-model="form.zeroCategoryCode"
                allow-clear
                dict-type="zeroLevelCategory"
                placeholder="请选择"
                @change="(row) => zeroCategory(row)"
              ></dict-select>
            </a-form-item>
            <a-form-item
              field="listNum"
              label="累计控制项"
              label-col-flex="100px"
            >
              <a-input v-model="form.listNum" disabled />
              <!-- <span>{{  form.listNum}}</span> -->
            </a-form-item>
            <a-form-item field="remarks" label="备注" label-col-flex="100px">
              <a-textarea
                v-model="form.remarks"
                placeholder="请输入备注"
                allow-clear
              />
            </a-form-item>
            <a-form-item field="creator" label="编制人" label-col-flex="100px">
              <span>{{ form.creator }}</span>
            </a-form-item>
            <a-form-item
              field="createTime"
              label="编制时间"
              label-col-flex="100px"
            >
              <span>{{ form.createTime }}</span>
            </a-form-item>
            <a-form-item
              field="undertakingUnit"
              label="承办单位"
              label-col-flex="100px"
            >
              <span>{{ form.undertakingUnit }}</span>
            </a-form-item>
            <a-form-item
              field="undertakingUnit"
              label="附件上传"
              label-col-flex="100px"
            >
              <span style="color: #8b8b8b"
                >文件大小不超过10M,支持pdf、doc、docx、zip文件格式</span
              >
            </a-form-item>
            <fileUpload
              v-model="fileValueList"
              multiple
              show-file-upload
              :show-file-list="true"
              :file-list="defaultList"
              btn-name="选择文件"
              btn-type="primary"
              accept=".xlsx,.pdf,.doc,.docx"
              title="单一控制来源清单文件上传"
            />
          </a-form>
          <a-space class="form-btn">
            <a-button @click="handleClose">取消</a-button>
            <a-button type="primary" @click="handleOk">保存</a-button>
          </a-space>
        </div>
      </template>
      <template #container-side>
        <a-button
          v-permission="['base:unique-control-detail:save']"
          type="primary"
          :disabled="!mainTableId"
          @click="addListData"
          >新增</a-button
        ><a-button
          v-permission="['base:unique-control-detail:delete']"
          :disabled="selectedKeys.length === 0"
          @click="removeListData"
          >删除</a-button
        >
        <block v-permission="['base:unique-control-detail:export']">
          <batchImport
            v-if="mainTableId"
            :cols="cols"
            file-code="infra_singleSource"
            :import-url="`/api/procurement/infra/unique-control-detail/import/${mainTableId}/1`"
            export-type="apiUrl"
            title="单一来源控制清单明细导入"
            btn-tititle="导入"
            :filter-secret-level="form.secretLevel"
            :before-open="beforeOpen"
            @close-drawer="importData"
            @finish="importData"
          ></batchImport>
        </block>
      </template>
      <template #operate="{ record }">
        <a-button
          v-permission="['base:unique-control-detail:update']"
          type="text"
          @click="editListData(record)"
          >编辑</a-button
        >
        <a-button
          v-permission="['base:unique-control-detail:delete']"
          type="text"
          @click="removeListData(record)"
          >删除</a-button
        >
      </template>
    </query-page>
    <myModal
      v-if="showModal"
      :main-table-id="mainTableId"
      :details-id="detailsId"
      :secret-level="form.secretLevel"
      :title="subtableTitle"
      @close="closeModal"
      @subtable-refresh="importData"
    ></myModal>
  </contentModel>
</template>

<script lang="ts" setup>
  import { ref, defineAsyncComponent } from 'vue';
  import secretLevelSelect from '@/common/components/cac-components/secret-level-select/index.vue';
  import contentModel from '@/common/components/content-model/index.vue';
  import queryPage from '@/common/components/query-page/index.vue';
  import dictSelect from '@/common/components/dict-select/index.vue';
  import inputModal from '@/common/components/search-modal/input-modal.vue';
  import batchImport from '@/common/components/batch-import/index.vue';
  import useModal from '@/common/hooks/modal';
  import fileUpload from '@/common/components/file-upload-page/index.vue';
  import { Modal, Message } from '@arco-design/web-vue';
  import {
    addMainTable,
    editMainTable,
    getOrderDetailsList,
    delSubTable,
  } from '@/api/Basimanagementapi/categorymanagement'; // 接口参数
  import { useUserStore } from '@/store';
  // import lodash from 'lodash';
  import { columns, tableRenderKeys } from './Singlelistcolumsadd';

  const myModal = defineAsyncComponent(
    () =>
      import('@/views/basic-configuration/singlelist/Singleaddmodal-modal.vue')
  );
  const { showModal, openModal, closeModal } = useModal();
  const cols = ref([
    {
      title: '姓名',
      dataIndex: 'name',
    },
  ]);
  const rules = ref({
    secretLevel: [{ required: true, message: '请选择密级' }],
  });
  const fileValueList = ref([]);
  const defaultList = ref([]);
  // 获取当前时间
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = currentDate.getMonth() + 1; // 注意月份是从0开始计数的，所以需要加1
  const day = currentDate.getDate();
  // 表格声明
  const selectedKeys = ref([]);
  const isLoading = ref(false);
  const total = ref(0);

  const form = ref({});
  const props = defineProps({
    title: {
      type: String,
      default: '',
    },
    dataListEdit: {
      type: Object,
      default: () => {
        return {};
      },
      required: false,
    },
    editId: {
      type: String,
      default: '',
    },
  });

  const handleSubmit = (data: any) => {
    console.log(data);
  };
  const mainTableId = ref();
  const formRef = ref();
  const handleOk = async () => {
    const verifyStatus = await formRef.value?.validate();
    if (!verifyStatus) {
      form.value.fileMessageList = fileValueList.value;
      if (props.title === '新增' && !mainTableId.value) {
        const { data } = await addMainTable(form.value);
        if (data) Message.success('新增成功');
        form.value.id = data;
        mainTableId.value = data;
        // fileValueList.value = form.value?.fileMessageList;
      } else {
        const { data } = await editMainTable(form.value);
        if (data) Message.success('编辑成功');
      }
    }
  };
  const emit = defineEmits(['close']);
  const handleClose = () => {
    emit('close');
    emit('refresh1');
  };
  const subtableListData = ref();
  const userData = useUserStore();
  const queryFormData = ref();
  const getData = async (queryForm: any) => {
    queryFormData.value = queryForm;
    if (props.title === '编辑') {
      mainTableId.value = props.editId;
      form.value = props.dataListEdit;
      defaultList.value = props.dataListEdit.fileMessageList;
      console.log(defaultList.value);

      const params = {
        ...queryForm,
        uniqueControlId: mainTableId.value,
      };
      const { data } = await getOrderDetailsList(params);
      subtableListData.value = data.list;
      total.value = data.total;
      form.value.listNum = data.total;
    } else {
      mainTableId.value = '';
      form.value.creator = userData.$state.username;
      form.value.undertakingUnit = userData.$state.deptCode;
      form.value.createTime = `${year}-${month}-${day}`;
    }
  };
  // MJ修改
  const secretLevelChange = () => {
    form.value.projectName = '';
  };
  // 零级品类选择
  const zeroCategory = (row: any) => {
    form.value.zeroCategoryName = row.label;
  };
  // 机型选择
  const selectSupplier = (row: any) => {
    form.value.projectName = row.materialName;
  };
  //
  const projectIdTips = () => {
    Message.warning('请先选择密级');
  };
  // 导入文件
  const beforeOpen = (cb) => {
    if (!mainTableId.value) {
      Modal.info({
        title: '提示',
        content: '导入数据前需要保存当前表单,你确认继续导入吗',
        hideCancel: false,
        onOk: async () => {
          const { data: res } = await addMainTable(form.value);
          mainTableId.value = res;
          if (res) Message.success('保存成功');
        },
      });
      return;
    }
    cb();
  };
  // 导入数据
  const importData = async (response, secretLevel) => {
    console.log(response, secretLevel, 'response, secretLevel');
    const params = {
      ...queryFormData.value,
      uniqueControlId: mainTableId.value,
    };
    const { data: res } = await getOrderDetailsList(params);
    subtableListData.value = res.list;
    form.value.listNum = res.total;
  };
  const subtableTitle = ref();
  // 添加子表数据
  const addListData = () => {
    subtableTitle.value = '新增';
    detailsId.value = '';
    openModal();
  };
  // 删除子表数据
  const removeListData = async (record: any) => {
    const ids = record.id ? [record.id] : selectedKeys.value;
    Modal.info({
      title: '提示',
      content: '您确定要删除当前所选的数据?',
      hideCancel: false,
      onOk: async () => {
        const { data } = await delSubTable(ids);
        if (data) Message.success('删除成功');
        importData();
      },
    });
  };
  // 编辑子表数据
  const detailsId = ref();
  const editListData = (row: any) => {
    subtableTitle.value = '编辑';
    detailsId.value = row.id;
    openModal();
  };
  // const collapsed = ref(false);
  // const onCollapse = () => {
  //   collapsed.value = !collapsed.value;
  // };
</script>

<style lang="less" scoped>
  .leftbox {
    position: relative;
    // width: 20%;
    height: 100%;
    padding: 5px;
    overflow-y: auto;

    ::-webkit-scrollbar {
      /*滚动条整体样式*/
      width: 9px; /*高宽分别对应横竖滚动条的尺寸*/
      height: 80px;
    }
    ::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/
      border-radius: 10px;
      background: rgb(var(--gray-4));
    }
    ::-webkit-scrollbar-track {
      /*滚动条里面轨道*/
      border-radius: 10px;
    }

    .form-btn {
      position: absolute;
      bottom: 0;
      left: 0;
      display: flex;
      align-items: center;
      width: 100%;
      height: 60px;
      background-color: #fff;
      box-shadow: 0 -2px 8px #ddd;
    }
  }
  .IconCare {
    width: 10px;
    height: 10px;
    border-bottom: 2px solid #ccc;
  }
  .l {
    border-left: 2px solid #ccc;
    transform: rotateZ(-135deg);
  }
  .r {
    border-right: 2px solid #ccc;
    transform: rotateZ(135deg);
  }
  .layout-demo {
    height: calc(100vh - 235px);
  }
  .layout-demo :deep(.arco-layout-content) {
    color: var(--color-text-2);
    font-weight: 400;
    font-size: 14px;
  }
  .layout-demo :deep(.arco-layout-content) {
    display: flex;
    flex-direction: column;
    justify-content: center;
    font-size: 16px;
    font-stretch: condensed;
  }
</style>
